﻿using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SmartPlant.Services
{
    /// <summary>
    /// 用户授权服务。对应administrator和intools user接口
    /// </summary>
    public class OAuthService : BaseService, IOAuthService
    {
        private decimal ProjId => GlobalObject.CurrentProject.ProjId;

        #region admin
        public async Task<List<UserRightData>> GetUserRightDatasAsync(string projId, string userId)
        {
            if (userId.IsNullOrEmpty()) throw new ArgumentNullException(nameof(userId));

            string uri = $"/api/Project/{projId}/user-right/getuserrights/{userId}";
            var res = await GetAsync<List<UserRightData>>(uri);
            return res.data;
        }

        public async Task<string> SwitchServerAsync(string configId)
        {
            if (configId.IsNullOrEmpty()) throw new ArgumentNullException(nameof(configId));

            string uri = $"/api/administrator/admin-conn/{configId}";
            var res = await GetAsync<string>(uri);
            return res.data;
        }
        /// <summary>
        /// 暂时没用到
        /// </summary>
        /// <param name="serverInfo"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public async Task<string> GetServerInfoAsync(ServerInfo serverInfo)
        {
            if (serverInfo == null) throw new ArgumentNullException(nameof(serverInfo));

            string Databasetype = serverInfo.Databasetype == "ORA" ? "3" : "1";
            string uri = $"/api/administrator/admin-conn-with-ini/{serverInfo.Profilename}/{serverInfo.Database}/{serverInfo.Servername}/{Databasetype}/{serverInfo.Username}/{serverInfo.Password}/{serverInfo.Port}";
            var res = await GetAsync<string>(uri);
            return res.data;
        }


        public async Task<List<ServerConfig>> GetConfigsAsync()
        {
            string uri = $"/api/administrator/configs";
            var res = await GetAsync<List<ServerConfig>>(uri);
            return res.data;
        }

        public async Task<List<ServerConfig>> TestServerAsync(string serverAddress)
        {
            if (serverAddress.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(serverAddress));

            string uri = $"/api/administrator/configs";
            var res = await GetAsync<List<ServerConfig>>(uri, null, () => serverAddress);
            return res.data;
        }
        #endregion

        #region intool-user
        //public async Task<LoginOutput> TestLoginAsync(LoginInfo input)
        //{
        //    string uri = "/oauth/Login";
        //    input.pwd = Md5Hash(input.pwd);
        //    var data = await PostFormAsync<LoginOutput, LoginInfo>(uri, input, "application/x-www-form-urlencoded");
        //    //this.AuthorizationCode = data.data.token;
        //    return data.data;
        //}



        public async Task<RESTfulResult<string>> LoginAsync(LoginInfo loginInput)
        {
            if (loginInput.user.IsNullOrEmpty()) throw new ArgumentNullException(nameof(loginInput.user));
            if (loginInput.pwd.IsNullOrEmpty()) throw new ArgumentNullException(nameof(loginInput.pwd));
            if (loginInput.dynamicConfigId.IsNullOrEmpty()) throw new ArgumentNullException(nameof(loginInput.dynamicConfigId));

            loginInput.pwd = Md5Hash(loginInput.pwd.ToUpper());//自动转大写
            string uri = $"/api/intools-user/login";
            var data = await PostBodyAsync<string, LoginInfo>(uri, loginInput);
            return data;
        }
        #endregion

        #region UserGroup
        /// <summary>
        /// 查所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserGroup>> GetAllUserGroupList()
        {
            string uri = $"/api/Project/{ProjId}/user-group-api/list";
            var res = await GetAsync<List<UserGroup>>(uri);
            return res.data;
        }

        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        /// <returns></returns>
        public async Task<UserGroup> GetUserGroupById(string id)
        {
            string uri = $"/api/Project/{ProjId}/user-group-api/info/{id}";
            var res = await GetAsync<UserGroup>(uri);
            return res.data;
        }

        /// <summary>
        /// 查所有
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> DeleteUseGrouprById(string id)
        {
            string uri = $"/api/Project/{ProjId}/user-group-api/{id}";
            var res = await DeleteAsync<bool?>(uri);
            return res.data;
        }


        /// <summary>
        /// 查所有
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> UpdateUserGroupr(UserGroup user)
        {
            string uri = $"/api/Project/{ProjId}/user-group-api";
            var res = await PutBodyAsync<bool?, UserGroup>(uri, user);
            return res.data;
        }

        /// <summary>
        /// 查所有
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> CreateUserGroupr(UserGroup user)
        {
            string uri = $"/api/Project/{ProjId}/user-group-api";
            var res = await PostBodyAsync<bool?, UserGroup>(uri, user);
            return res.data;
        }

        /// <summary>
        /// 分配到用户组（原则上一个用户只属于一个用户组）
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> AssignToGroup(string userId, string groupId)
        {
            string uri = $"/api/Project/{ProjId}/user-group-api/assigntogroup/{userId}/{groupId}";
            var res = await PostAsync<bool?>(uri);
            return res.data;
        }

        /// <summary>
        /// 从用户组中移除
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> UnAssignFromGroup(string userId, string groupId)
        {
            string uri = $"/api/Project/{ProjId}/user-group-api/unassignfromgroup/{userId}/{groupId}";
            var res = await PostAsync<bool?>(uri);
            return res.data;
        }
        #endregion

        #region User
        /// <summary>
        /// 查所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<IntoolsUser>> GetAllUserList()
        {
            string uri = $"/api/intools-user/list/{GlobalObject.CurrentProject.ProjId.ToString()}";
            var res = await GetAsync<List<IntoolsUser>>(uri);
            return res.data;
        }

        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        /// <returns></returns>
        public async Task<IntoolsUser> GetUserByName(string userName)
        {
            string uri = $"/api/intools-user/info/{userName}";
            var res = await GetAsync<IntoolsUser>(uri);
            return res.data;
        }

        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        /// <returns></returns>
        public async Task<IntoolsUser> GetUserById(string userId)
        {
            string uri = $"/api/intools-user/info/id/{userId}";
            var res = await GetAsync<IntoolsUser>(uri);
            return res.data;
        }

        /// <summary>
        /// 删除某个
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> DeleteUserById(string id)
        {
            string uri = $"/api/intools-user/{id}";
            var res = await DeleteAsync<bool?>(uri);
            return res.data;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> UpdateUser(IntoolsUser user)
        {
            string uri = $"/api/intools-user";
            var res = await PutBodyAsync<bool?, IntoolsUser>(uri, user);
            return res.data;
        }

        /// <summary>
        /// 查所有
        /// </summary>
        /// <returns></returns>
        public async Task<bool?> CreateUser(IntoolsUser user)
        {
            string uri = $"/api/intools-user";
            var res = await PostBodyAsync<bool?, IntoolsUser>(uri, user);
            return res.data;
        }

        /// <summary>
        /// 获取《组》权限列表（所有unit）
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public async Task<List<UserRightData>> GetGroup(string groupid)
        {
            string uri = $"/api/Project/{ProjId}/user-right/group/{groupid}";
            var res = await GetAsync<List<UserRightData>>(uri);
            return res.data;
        }

        /// <summary>
        /// 权限分配（按Unit）
        /// </summary>
        /// <param name="data"></param>
        /// <param name="groupId"></param>
        /// <param name="unitId"></param>
        /// <returns></returns>
        public async Task<bool?> SetGroup(List<UserRightData> data, string groupId, string unitId)
        {
            string uri = $"/api/Project/{ProjId}/user-right/set-group/{groupId}/{unitId}";
            var res = await PostBodyAsync<bool?, List<UserRightData>>(uri, data);
            return res.data;
        }

        public async Task<bool?> SetGlobalGroup(int access, string groupId)
        {
            string uri = $"/api/Project/{ProjId}/user-right/set-global-group/{access}/{groupId}";
            var res = await PostAsync<bool>(uri);
            return res.data;
        }
        #endregion


    }
}
